#!/bin/bash

# utilities
TR='tr'
WC='wc'
PS='ps'
SED='sed'
TOP='top'
GREP='grep'
PSTREE='pstree'

# print error message
log_failure_msg () {
  if [ -n "${1:-}" ]; then
    /bin/echo "$@" || true
  fi
}

# checking ... print lines matching a pattern utility
if ! echo a | $GREP -E '(a|b)' >/dev/null 2>&1; then
  log_failure_msg "$0: error: $GREP utility not found."
fi

# checking ... word count utility
if ! $WC --version >/dev/null 2>&1; then
  log_failure_msg "$0: error: $WC utility not found."
fi

# checking ... stream editor utility
if ! $SED --version >/dev/null 2>&1; then
  log_failure_msg "$0: error: $SED utility not found."
fi

# checking ... delete characters utility
if ! $TR --version >/dev/null 2>&1; then
  log_failure_msg "$0: error: $TR utility not found."
fi

# checking ... display a tree of processes utility
if ! $PSTREE --version >/dev/null 2>&1; then
  log_failure_msg "$0: error: $PSTREE utility not found."
fi

# checking ... report a snapshot of the current processes utility.
if ! $PS --version >/dev/null 2>&1; then
  log_failure_msg "$0: error: $PS utility not found."
fi

# checking ... display Linux processes utility.
if ! $TOP -v >/dev/null 2>&1; then
  log_failure_msg "$0: error: $TOP utility not found."
fi

# get the loolwsd process id.
LOOLWSD_PID=`pgrep loolwsd$`;

# checking if loolwsd is running.
if ! $PS -p $LOOLWSD_PID > /dev/null; then
	log_failure_msg "$0: error: loolwsd is not running."
	exit 1;
fi

# display a tree of processes.
$PSTREE -a -c -h -A -p $LOOLWSD_PID;

# get the number of running processes.
PROCESS=$($PSTREE -a -h -A -p $LOOLWSD_PID | $SED -e "s/\`//g" | $TR -d ' |-' | $GREP -E '^loolwsd|^loolforkit|^loolkit' | $WC -l);

# get the number of running threads.
THREADS=$($PSTREE -a -h -A -p $LOOLWSD_PID | $GREP -o '{.*}' | $WC -l);

# get the number of running client socket.
LOOLWSD_CLIENT=$($PSTREE -a -h -A -p $LOOLWSD_PID | $GREP -o '{client_socket}' | $WC -l);

# get the number of running prision socket.
LOOLWSD_PRISIONER=$($PSTREE -a -h -A -p $LOOLWSD_PID | $GREP -o '{prision_socket}' | $WC -l);

# get the number of processes swapped out.
SWAPPEDOUT=$($PSTREE -a -h -A -p $LOOLWSD_PID | $GREP -o '(.*)' | $WC -l);

# display report stats
printf "\n %-10s\n" "LOOLWSD STATS";
printf "==========================\n";
printf " %-10s %d\n" "Running process:" "$PROCESS";
printf " %-10s %d\n" "Running threads:" "$THREADS";
printf " %-10s %d\n" "Process swapped out:" "$SWAPPEDOUT";
printf " %-10s %d\n" "Socket Client   threads:" "$LOOLWSD_CLIENT";
printf " %-10s %d\n" "Socket Prision  threads:" "$LOOLWSD_PRISIONER";
$TOP -bn 1 | $GREP -E 'loolwsd|COMMAND'

